package com.inche.camerademo;
import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureFailure;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.provider.MediaStore;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.inche.camerademo.R;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class Demo2Activity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "Camera2Demo";
    private static final int REQUEST_CAMERA_PERMISSION = 1;
    private Surface mPreviewSurface;   // 给预览+录像共用
//    防止图片和视频在图库方向是乱的
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    CameraManager manager = null;
    private TextureView textureView;
    private CameraDevice cameraDevice;
    private CameraCaptureSession captureSession;
    private CaptureRequest.Builder previewBuilder;
    private Size previewSize;
    private String cameraId;
    private Handler backgroundHandler;
    private HandlerThread backgroundThread;
    private ImageReader imageReader;
    private MediaRecorder mediaRecorder;
    private boolean isRecording = false;
    private volatile boolean isBursting = false;   // 是否正在连拍
    private final int BURST_MAX = 30;              // 最多连拍 30 张，防止卡死
//
    private boolean isFrontCamera = true;
    private StreamConfigurationMap map;
    private ImageView imageView;

    private boolean isContinuousCapture = false;
    private View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN){
                shutterButton(true);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                isContinuousCapture = false;
                shutterButton(false);
            }

            return false;
        }
    };
    private View.OnLongClickListener mOnLongClickListener = new View.OnLongClickListener(){

        @Override
        public boolean onLongClick(View v) {
            isContinuousCapture = true;
            return false;
        }
    };

    private void shutterButton(boolean pressed) {
        if (pressed && !isContinuousCapture) {      // 单拍
            takePicture();
        } else if (pressed && isContinuousCapture) { // 连拍
            startBurst();
        } else {                                    // 手指抬起
            stopBurst();
        }
    }
    private final Runnable burstTask = new Runnable() {
        private int count = 0;

        @Override
        public void run() {
            if (!isBursting || count >= BURST_MAX) {
                count = 0;          // 下次还能再拍
                return;
            }
            takePicture();
            count++;
            // 120 ms 节流，拍太快没意义
            backgroundHandler.postDelayed(this, 120);
        }
    };

    private void startBurst() {
        isBursting = true;
        backgroundHandler.post(burstTask);
    }

    private void stopBurst() {
        isBursting = false;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo2);

        textureView = findViewById(R.id.texture_view);
        Button btnCapture = findViewById(R.id.btn_capture);
        btnCapture.setOnTouchListener(mOnTouchListener);
        btnCapture.setOnLongClickListener(mOnLongClickListener);
        Button btnRecord = findViewById(R.id.btn_record);
        Button btnOpen    = findViewById(R.id.btn_open);
        Button btnClose   = findViewById(R.id.btn_close);
        Button btnGallery = findViewById(R.id.btn_gallery);
        Button btn_switch = findViewById(R.id.btn_switch);
//        imageView = findViewById(R.id.iv_look);



        btnCapture.setOnClickListener(this);
        btnRecord.setOnClickListener(this);
        btnOpen.setOnClickListener(this);
        btnClose.setOnClickListener(this);
        btnGallery.setOnClickListener(this);
        btn_switch.setOnClickListener(this);


//        创建监听事件



    }

    @Override
    protected void onResume() {
        super.onResume();
        init();
        textureView.setSurfaceTextureListener(surfaceTextureListener);
        Log.d(TAG,"onResume");
        startBackgroundThread();

        if (textureView.isAvailable()) {
            openCamera();
        }
    }



    @Override
    protected void onPause() {
        super.onPause();
        closeCamera();
        stopBackgroundThread();
        imageReader.close();

    }
    @Override
    public void onClick(View v) {
//        if (v.getId() == R.id.btn_capture) {
//            Log.d(TAG, "onClick: 点击出发");
//            takePicture();
//        } else
        if (v.getId() == R.id.btn_record) {
            if (isRecording) {
                stopRecording();
            } else {
                startRecording();
            }
        } else if (v.getId() == R.id.btn_open) {
            openCamera();          // 直接复用已有方法
        } else if (v.getId() == R.id.btn_close) {
            closeCamera();         // 直接复用已有方法
        } else if (v.getId() == R.id.btn_gallery) {
            // 跳转到系统图库
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/* video/*"); // 可看照片也可看视频
            startActivity(intent);
        } else if (v.getId()==R.id.btn_switch) {
            isFrontCamera = !isFrontCamera;
            closeCamera();
            openCamera();
        }
    }




    //    关闭相机
    private void closeCamera() {
        Log.d(TAG, "sjm123: ");
        try {
            if (captureSession != null) {
                captureSession.close();
                captureSession = null;
            }
            if (cameraDevice != null) {
                cameraDevice.close();
                cameraDevice = null;
            }
//            if (imageReader != null) {
//                imageReader.close();
//            }
            if (mediaRecorder != null) {
                mediaRecorder.release();
                mediaRecorder = null;
            }
        } catch (Exception e) {
            Log.e(TAG, "关闭相机失败", e);
        }
    }


//监听事件
    private final TextureView.SurfaceTextureListener surfaceTextureListener =
            new TextureView.SurfaceTextureListener() {
//        当textureView可用时 执行openCamera
                @Override
                public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
                    openCamera();
                }
//          当这个幕布旋转或者改变尺寸时
                @Override
                public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {}

//                当这个幕布被销毁时
                @Override
                public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
                    closeCamera();
                    return true;
                }
//            当这个幕布更新时
                @Override
                public void onSurfaceTextureUpdated(SurfaceTexture texture) {

                }
            };

//       打开相机

    private void init() {
        manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            if (isFrontCamera) {
                cameraId = manager.getCameraIdList()[0];
                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); // hal下发 获取相机的数据
                map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            } else {
                cameraId = manager.getCameraIdList()[1];
                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
                map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            }
            previewSize = getOptimalSize(map.getOutputSizes(SurfaceTexture.class)); // 获取合适的预览尺寸
        } catch (Exception e) {
            Log.e(TAG, "初始化失败", e);
        }
    };

    private void openCamera() {
        try{
            // 请求权限
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestCameraPermission();
                return;
            }
            manager.openCamera(cameraId, stateCallback, backgroundHandler);
        } catch (CameraAccessException e) {
            Log.e(TAG, "打开相机失败", e);
        }
    }
// 获取合适预览尺寸方法
    private Size getOptimalSize(Size[] sizes) {
        for (Size size : sizes) {
            if (size.getWidth() <= 1920 && size.getHeight() <= 1080) {
                return size;
            }
        }
        return sizes[0];
    }

//    相机的回调函数 与创建流的函数都在这里
    private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
//        能够打开相机
        @Override
        public void onOpened(@NonNull CameraDevice camera) {
            cameraDevice = camera;
//            执行captureSession创建  将一帧一帧的数据传递到幕布中去
            configSession();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice camera) {
            camera.close();
            cameraDevice = null;
        }

        @Override
        public void onError(@NonNull CameraDevice camera, int error) {
            camera.close();
            cameraDevice = null;
        }
    };

//    预览
private void configSession() {
    try {
        SurfaceTexture texture = textureView.getSurfaceTexture();
        texture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight());
        mPreviewSurface = new Surface(texture);          // ① 预览/录像共用

        // ② 拍照专用 ImageReader
        if (imageReader == null) {
            imageReader = ImageReader.newInstance(
                    previewSize.getWidth(), previewSize.getHeight(),
                    ImageFormat.JPEG,   /*maxImages*/1);
            imageReader.setOnImageAvailableListener(listener, backgroundHandler);
        }

        List<Surface> outputs = Arrays.asList(
                mPreviewSurface,           // 流1：预览/录像
                imageReader.getSurface()); // 流2：拍照

        cameraDevice.createCaptureSession(outputs,
                new CameraCaptureSession.StateCallback() {
                    @Override public void onConfigured(@NonNull CameraCaptureSession s) {
                        captureSession = s;
                        updatePreview();          // 先跑预览
                    }
                    @Override public void onConfigureFailed(@NonNull CameraCaptureSession s) {
                        Log.e(TAG, "双输出配置失败");
                    }
                }, backgroundHandler);
    } catch (CameraAccessException e) {
        Log.e(TAG, "configSession 失败", e);
    }
}

    private void updatePreview() {
        try {
            previewBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            previewBuilder.addTarget(mPreviewSurface);
            captureSession.setRepeatingRequest(previewBuilder.build(), null, backgroundHandler);
        } catch (CameraAccessException ignore) {}
    }





    ImageReader.OnImageAvailableListener listener = reader -> {
        Image image = null;
        try {
            image = reader.acquireLatestImage(); //取出照片赋值
            ByteBuffer buffer = image.getPlanes()[0].getBuffer(); //拿到字节缓冲区
            byte[] bytes = new byte[buffer.remaining()]; //剩余多少字节
            buffer.get(bytes); //把缓冲区里的数据复制到字节数组里
            saveImage(bytes); //保存照片
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if (image != null) image.close();
        }
//             // 确保关闭ImageReader
    };
    public void continuousCapture(){


    }


    private void takePicture() {
        try {
            Log.d(TAG, "takePicture: 1111");
            CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);

            captureBuilder.addTarget(imageReader.getSurface());
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, 90);
            captureBuilder.set(CaptureRequest.CONTROL_AE_MODE,CaptureRequest.FLASH_MODE_TORCH);
            CaptureRequest build = captureBuilder.build();
            Log.d(TAG, "takePicture: 2222");
            captureSession.capture(build, new CameraCaptureSession.CaptureCallback() {

                @Override
                public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
                    Log.d(TAG, "抓帧开始");
                    super.onCaptureStarted(session, request, timestamp, frameNumber);
                }

                @Override
                public void onReadoutStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
                    super.onReadoutStarted(session, request, timestamp, frameNumber);
                    Log.d(TAG, "onReadoutStarted: 12");
                }

                @Override
                public void onCaptureProgressed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureResult partialResult) {
                    super.onCaptureProgressed(session, request, partialResult);
                    Log.d(TAG, "onReadoutStarted: 123");
                }

                @Override
                public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) {
                    super.onCaptureFailed(session, request, failure);
                    Log.d(TAG, "onReadoutStarted: 1234");
                }

                @Override
                public void onCaptureSequenceCompleted(@NonNull CameraCaptureSession session, int sequenceId, long frameNumber) {
                    super.onCaptureSequenceCompleted(session, sequenceId, frameNumber);
                    Log.d(TAG, "onReadoutStarted: 12345");
                }

                @Override
                public void onCaptureSequenceAborted(@NonNull CameraCaptureSession session, int sequenceId) {
                    super.onCaptureSequenceAborted(session, sequenceId);
                    Log.d(TAG, "onReadoutStarted: 123456");
                }

                @Override
                public void onCaptureBufferLost(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull Surface target, long frameNumber) {
                    super.onCaptureBufferLost(session, request, target, frameNumber);
                    Log.d(TAG, "onReadoutStarted: 1234567");
                }

                @Override
                public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
                    super.onCaptureCompleted(session, request, result);
                    updatePreview();
                    Log.d(TAG, "onCaptureCompleted: 抓真完成");
                }
            }, backgroundHandler);
        } catch (CameraAccessException e) {
            throw new RuntimeException(e);
        }



    }

    private void saveImage(byte[] bytes) {
        try {
            // 1. 创建 ContentValues 对象，用来向系统 MediaStore 描述“我要插入一条图片记录”
            ContentValues values = new ContentValues();
            // 2. 设置文件名：IMG_20240518_143027.jpg（当前时间）
            values.put(MediaStore.Images.Media.DISPLAY_NAME,
                    "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg");

            // 3. 设置 MIME 类型：告诉系统这是 JPEG 图片
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");

            // 4. Android 10 (Q) 及以上：指定保存到公共 DCIM 目录
            //    低于 Q 时 RELATIVE_PATH 会被忽略，文件仍存到共享 DCIM
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
            }

            // 5. 向 MediaStore 插入一条“空”记录，返回一条指向新文件的 content:// URI
            Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            // 6. 成功拿到 URI 才继续写文件，避免空指针
            if (uri != null) {
                // 7. 用 try-with-resources 打开该 URI 对应的输出流
                try (OutputStream os = getContentResolver().openOutputStream(uri)) {
                    // 8. 把之前得到的 JPEG 字节数组写入文件
                    os.write(bytes);
                    // 9. 切回主线程弹出 Toast，提示用户照片已保存
                    runOnUiThread(() -> Toast.makeText(this, "照片已保存", Toast.LENGTH_SHORT).show());
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "保存照片失败", e);
        }
    }

//    开始录制视频
    private void startRecording() {
        try {
            // 1. 初始化并配置 MediaRecorder（设置音视频源、格式、输出路径、码率等）
            setupMediaRecorder();

// 2. 从 TextureView 取出 SurfaceTexture，用于实时预览
            SurfaceTexture texture = textureView.getSurfaceTexture();

// 3. 把预览缓冲区的尺寸设成我们选好的 previewSize，防止拉伸或崩溃
            texture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight());

// 4. 创建列表，准备告诉相机“我要两路输出”
            List<Surface> surfaces = new ArrayList<>();

// 5. 第一路：预览 Surface → 让用户在屏幕上看到实时画面
            surfaces.add(new Surface(texture));

// 6. 第二路：MediaRecorder 的 Surface → 把相机画面编码进 MP4
            surfaces.add(mediaRecorder.getSurface());

// 7. 用“录像”模板生成 CaptureRequest.Builder，已预填连续 AF、抗闪烁等参数
            previewBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);

// 8. 把预览 Surface 挂到请求上，保证录像时屏幕仍有实时画面
            previewBuilder.addTarget(new Surface(texture));

// 9. 把 MediaRecorder 的 Surface 也挂到请求上，让编码器收到每一帧
            previewBuilder.addTarget(mediaRecorder.getSurface());

// 10. 创建新的捕获会话，传入两路 Surface + 回调 + 后台线程
            cameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
                // 11. 会话配置成功回调（异步）
                @Override
                public void onConfigured(@NonNull CameraCaptureSession session) {
                    try {
                        // 12. 用刚才的 Builder 发“连续请求”，让相机源源不绝地送帧
                        session.setRepeatingRequest(previewBuilder.build(), null, backgroundHandler);

                        // 13. 启动 MediaRecorder，开始把音视频编码成 MP4
                        mediaRecorder.start();

                        // 14. 标记正在录制
                        isRecording = true;

                        // 15. 切回主线程，弹 Toast 提示用户
                        runOnUiThread(() -> Toast.makeText(Demo2Activity.this, "开始录制", Toast.LENGTH_SHORT).show());
                    } catch (CameraAccessException e) {
                        // 16. 捕获异常并打印
                        Log.e(TAG, "开始录制失败", e);
                    }
                }

                // 17. 会话配置失败回调
                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                    Log.e(TAG, "配置录制失败");
                }
            }, backgroundHandler); // 18. 整个回调都在后台线程触发，避免卡 UI

// 19. 外层 try-catch：捕获 CameraAccessException 或 IOException（MediaRecorder.prepare()抛出的）
        } catch (CameraAccessException | IOException e) {
            Log.e(TAG, "准备录制失败", e);
        }
    }

    private void setupMediaRecorder() throws IOException {
        // 1. 新建 MediaRecorder 实例，作为“录像机”
        mediaRecorder = new MediaRecorder();

// 2. 设置音频来源：麦克风
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

// 3. 设置视频来源：来自相机 Surface（非摄像头硬件号，而是 Surface）
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);

// 4. 设置封装格式：MP4 容器
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

// 5. 创建 ContentValues，用于向系统 MediaStore 插入一条“空”视频记录
        ContentValues values = new ContentValues();

// 6. 设置文件名：VID_20240518_143027.mp4（当前时间）
        values.put(MediaStore.Video.Media.DISPLAY_NAME,
                "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4");

// 7. 设置 MIME 类型：告诉系统这是 MP4 视频
        values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");

// 8. Android 10(Q)及以上：指定保存到公共 Movies 目录
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            values.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_MOVIES);
        }

// 9. 向 MediaStore 插入一条空记录，返回指向新文件的 content:// URI
        Uri uri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);

// 10. 若成功拿到 URI，则继续配置 MediaRecorder
        if (uri != null) {
            // 11. 把 URI 转换成可写的文件描述符，作为录像输出文件
            mediaRecorder.setOutputFile(
                    getContentResolver().openFileDescriptor(uri, "w").getFileDescriptor()
            );

            // 12. 设置视频编码码率：10 Mbps（清晰度与体积折中）
            mediaRecorder.setVideoEncodingBitRate(10000000);

            // 13. 设置帧率：30 fps
            mediaRecorder.setVideoFrameRate(30);

            // 14. 设置视频分辨率：与相机预览尺寸一致，避免拉伸
            mediaRecorder.setVideoSize(previewSize.getWidth(), previewSize.getHeight());

            // 15. 设置视频编码器：H.264
            mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

            // 16. 设置音频编码器：AAC
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

            // 17. 设置视频方向提示：90°，解决横竖屏播放方向问题
            mediaRecorder.setOrientationHint(90);

            // 18. 完成所有配置，让 MediaRecorder 进入就绪状态
            mediaRecorder.prepare();
        }
    }

    private void stopRecording() {
        if (mediaRecorder != null) {
            try {
                mediaRecorder.stop();
            } catch (IllegalStateException e) {
                Log.w(TAG, "媒体录制器已停止", e);
            }
            mediaRecorder.reset();
            mediaRecorder.release();
            mediaRecorder = null;
            isRecording = false;
            runOnUiThread(() -> Toast.makeText(this, "视频已保存", Toast.LENGTH_SHORT).show());
//            startPreview();
        }
    }

//    权限申请
    private void requestCameraPermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO},
                REQUEST_CAMERA_PERMISSION);
    }

//    权限回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera();
            } else {
                Toast.makeText(this, "需要相机权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

//    后台线程绑定
    private void startBackgroundThread() {
        backgroundThread = new HandlerThread("CameraBackground");
        backgroundThread.start();
        backgroundHandler = new Handler(backgroundThread.getLooper());
    }

//    关闭线程
    private void stopBackgroundThread() {
        if (backgroundThread != null) {
            backgroundThread.quitSafely();
            try {
                backgroundThread.join();
            } catch (InterruptedException e) {
                Log.e(TAG, "线程中断", e);
            }
            backgroundThread = null;
            backgroundHandler = null;
        }
    }


}